﻿# -*- coding: utf-8 -*-
import socket
import threading
import logging

FORMAT = '%(asctime)s %(threadName)s %(thread)d [%(message)s]'
logging.basicConfig(format=FORMAT, level=logging.INFO, datefmt='%H:%M:%S')


class TCP_clinet:
    def __init__(self, ip='127.0.0.1', port=60000):
        self.raddr = ip, port
        self.client = socket.socket()
        self.event = threading.Event()

    def start(self):
        try:
            self.client.connect(self.raddr)
            threading.Thread(target=self.recv, name='recv').start()
            while True:
                In = input('>>>')
                if In == 'quit':
                    self.send('quit'.encode())
                    self.stop()
                    break
                else:
                    In = In.strip()
                    if In:
                        self.send(In.encode())
        except ConnectionRefusedError as e:
            logging.info('目标主机拒绝连接或者不在线！')

    def recv(self):
        while not self.event.is_set():
            try:
                data = self.client.recv(1024).decode().strip()
                print(data)
            except Exception as e:
                logging.warning(e)

    def send(self, Info):
        self.client.send(Info)

    def stop(self):
        self.event.set()
        self.client.close()


def run():
    cs = TCP_clinet()
    cs.start()


if __name__ == '__main__':
    run()
